<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="bookSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item>
          <el-input v-model="bookSearch.bname" placeholder="书名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="bookSearch.author" placeholder="作者"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="bookSearch.lid" placeholder="所在图书馆">
            <el-option label="所有图书馆" value="0"></el-option>
            <el-option :label="l.lname" :value="l.lid" v-for="l in libraryList" :key="l.lid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-search" plain @click="addBook">添加书籍</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="bookList"
          style="width: 100%">
        <el-table-column
            label="书号"
            align="center"
            prop="bid"
            width="180"/>
        <el-table-column
            label="书名"
            prop="bname"
            align="center"/>
        <el-table-column
            label="作者"
            prop="author"
            align="center"/>
        <el-table-column
            label="出版日期"
            prop="publishDate"
            align="center"/>
        <el-table-column
            label="所在图书馆"
            prop="lname"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页导航面板-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加书籍对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="book" :rules="rules" ref="ruleForm">
        <el-form-item label="书名" :label-width="formLabelWidth" prop="bname">
          <el-input v-model="book.bname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者" :label-width="formLabelWidth" prop="author">
          <el-input v-model="book.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版日期" :label-width="formLabelWidth" prop="publishDate">
          <el-date-picker
              v-model="book.publishDate"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所在图书馆" :label-width="formLabelWidth" prop="lid">
          <el-select v-model="book.lid" placeholder="请选择图书馆">
            <el-option :label="l.lname" :value="l.lid" v-for="l in libraryList" :key="l.lid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBook">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import libraryApi from "@/api/library"
import bookApi from "@/api/book"

export default {
  data() {
    // 自定义校验规则
    let checkPublishDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('出版日期不能为空'))
      } else {
        callback()
      }
    }
    return {
      bookList: [],
      page: 1,
      pageSize: 5,
      total: 100,
      bookSearch: {},
      libraryList: [],
      dialogFormVisible: false,
      book: {},
      title: '添加书籍',
      formLabelWidth: '120px',
      rules: {
        bname: [
          { required: true, message: '请输入书名', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        publishDate: [
          { validator: checkPublishDate, trigger: 'blur' }
        ],
        lid: [
          { required: true, message: '请选择图书馆', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.search()
    this.findAllLibraries()
  },
  methods: {
    async findBooks() {
      try {
        const { data: res } = await bookApi.findBooks()
        if (res.code === 200) {
          this.bookList = res.data.list
        }
      } catch (error) {
        console.error("查询所有书籍失败:", error)
      }
    },
    // 添加书籍
    addBook() {
      this.dialogFormVisible = true
      this.title = '添加书籍'
      this.book = {}
    },
    saveBook() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          let url = "/books/add"
          let method = "post"
          if (this.book.bid) {
            url = "/books/update"
            method = "put"
          }
          try {
            const { data: res } = await bookApi.saveBook(url, method, this.book)
            console.log("res:", res)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.search()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          } catch (error) {
            console.error("保存书籍失败:", error)
            this.$message({
              type: 'error',
              message: '保存书籍失败'
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    async findByPage() {
      const { data: res } = await bookApi.findByPage(this.page, this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.bookList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    async findAllLibraries() {
      try {
        const { data: res } = await libraryApi.findAllLibraries()
        if (res.code === 200) {
          this.libraryList = res.data.list
        }
      } catch (error) {
        console.error("查询所有图书馆失败:", error)
      }
    },
    async search() {
      try {
        // 在查询参数中加入 deleted: 0 的条件
        const { data: res } = await bookApi.searchBooks(this.page, this.pageSize, { ...this.bookSearch, deleted: 0 })
        if (res.code === 200) {
          this.bookList = res.data.pr.rows;
          this.total = res.data.pr.total;
        }
      } catch (error) {
        console.error("条件查询失败:", error);
      }
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      this.findByPage()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.page = val
      this.search()
      this.findByPage()
      console.log(`当前页: ${val}`);
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible = true
      this.title = '编辑书籍'
      this.book = { ...row }
    },
    async handleDelete(index, row) {
      try {
        const { data: res } = await bookApi.deleteBook(row.bid)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: res.message || '删除成功'
          })
          // 刷新列表，移除已删除的书籍
          this.search()
        } else {
          this.$message({
            type: 'error',
            message: res.message || '删除失败'
          })
        }
      } catch (error) {
        console.error("删除书籍失败:", error)
        this.$message({
          type: 'error',
          message: '删除书籍失败'
        })
      }
    },
  }
}
</script>

<style>
#app {
  display: flex;
  justify-content: center;
}
.el-card {
  width: 90%;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
